/*
 * Copyright (c) 2006-2017, Yunnan Sanjiu Network technology Co., Ltd.
 *
 * All rights reserved.
 */
package com.ng.finance.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * HttpClientUtil
 *
 * @author
 */
@Slf4j
public class HttpClientUtil {
    private static final String CHARSET_UTF_8 = "UTF-8";

    private static final String CONTENT_TYPE_JSON = "application/json";

    private static Logger logger = LoggerFactory.getLogger(com.ng.finance.common.util.HttpClientUtil.class);

    private static String BASE = "http://47.106.194.24:9222/";
    private static String UPLOAD = "http://47.106.194.24:9333/submit";
    private static String SELECT = "http://file.liuguohai.com";


    private static void doHttpClientClose(CloseableHttpClient httpClient) {
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发送get请求
     *
     * @param url
     * @return
     */
    public static String get(String url) {
        String res = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            URL url1 = null;
            try {
                url1 = new URL(url);
                URI uri = new URI(url1.getProtocol(), url1.getHost(), url1.getPath(), url1.getQuery(), null);
                HttpGet httpGet = new HttpGet(uri);
                httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
                res = execute(httpClient, httpGet);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
        } finally {
            doHttpClientClose(httpClient);
        }
        return res;
    }

    public static String get(String url, String cookie) {
        String res = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            URL url1 = null;
            try {
                url1 = new URL(url);
                URI uri = new URI(url1.getProtocol(), url1.getHost(), url1.getPath(), url1.getQuery(), null);
                HttpGet httpGet = new HttpGet(uri);
                httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
                httpGet.setHeader("Cookie", cookie);
                res = execute(httpClient, httpGet);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
        } finally {
            doHttpClientClose(httpClient);
        }
        return res;
    }

    public static String getByHeaderCity(String url, String city) {
        String res = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            URL url1 = null;
            try {
                url1 = new URL(url);
                URI uri = new URI(url1.getProtocol(), url1.getHost(), url1.getPath(), url1.getQuery(), null);
                HttpGet httpGet = new HttpGet(uri);
                httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
                httpGet.setHeader("city", city);
                res = execute(httpClient, httpGet);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
        } finally {
            doHttpClientClose(httpClient);
        }
        return res;
    }


    /**
     * 发送post请求
     *
     * @param url    post url
     * @param params post参数
     * @return
     */
    public static String post(String url, Map<String, String> params) {
        String res = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost httpPost = httpPostHandler(url, params);
            res = execute(httpClient, httpPost);
        } finally {
            doHttpClientClose(httpClient);
        }
        return res;
    }

    /**
     * 发送delete请求
     *
     * @param url 请求地址
     *            返回数据编码
     * @return String
     */
    public static String sndDelete(String url) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpDelete del = new HttpDelete(url);
        try {
            // 提交请求并以指定编码获取返回数据
            HttpResponse httpResponse = httpClient.execute(del);
            logger.info("请求地址：" + url + "；响应状态：" + httpResponse.getStatusLine());
            HttpEntity entity = httpResponse.getEntity();
            return EntityUtils.toString(entity, CHARSET_UTF_8);
        } catch (ClientProtocolException e) {
            logger.error("协议异常,堆栈信息如下", e);
        } catch (IOException e) {
            logger.error("网络异常,堆栈信息如下", e);
        } finally {
            // 关闭连接，释放资源
            try {
                httpClient.close();
            } catch (Exception e) {
                e.printStackTrace();
                httpClient = null;
            }
        }
        return null;
    }

    /**
     * post json数据
     *
     * @param url
     * @param jsonStr
     * @return
     */
    public static String postJson(String url, String jsonStr) {
        String res = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(url);
            StringEntity stringEntity;
            try {
                stringEntity = new StringEntity(jsonStr);
            } catch (UnsupportedEncodingException e) {
                return null;
            }
            httpPost.setHeader("Content-Type", CONTENT_TYPE_JSON);
            httpPost.setEntity(stringEntity);
            res = execute(httpClient, httpPost);
        } finally {
            doHttpClientClose(httpClient);
        }
        return res;
    }


    public static void main(String[] args) {
        long millis = System.currentTimeMillis();


    }


    private static ContentType getContentType(MultipartFile multipartFile) {
        String contentType = multipartFile.getContentType();
        ContentType mimeType = ContentType.getByMimeType(contentType);
        if (mimeType == null) {
            mimeType = ContentType.create(contentType, "UTF-8");
        }
        return mimeType;
    }


    private static String[] changeFid(String fileName, String fid) {
        String[] gather = new String[2];
        if (fileName.contains(".")) {
            gather[0] = fileName.substring(fileName.lastIndexOf(".") + 1);
            gather[1] = fid.replace(",", "/") + "." + gather[0];
            return gather;
        }
        gather[0] = null;
        gather[1] = fid.replace(",", "/");
        return gather;
    }


    private static HttpPost httpPostHandler(String url, Map<String, String> params) {
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> nvps = new ArrayList<>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, CHARSET_UTF_8));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return httpPost;
    }

    private static String execute(CloseableHttpClient httpClient, HttpUriRequest httpGetOrPost) {
        String res = null;
        int statusCode = 0;
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGetOrPost);
            HttpEntity entity = response.getEntity();
            statusCode = response.getStatusLine().getStatusCode();
            res = EntityUtils.toString(entity, CHARSET_UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            doResponseClose(response);
        }

        if (statusCode == HttpStatus.OK.value()) {
            return res;
        } else {

            return null;
        }
    }

    private static void doResponseClose(CloseableHttpResponse response) {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
